/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package org.game.netty.server;

import org.game.actor.msg.ClientMsg;
import org.game.constant.SessionConstent;
import org.game.module.Dispatcher;
import org.game.netty.oldcoder.other.IChannelConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sojoys.artifact.constant.ServerStatusEnum;
import com.sojoys.artifact.core.IServer;
import com.sojoys.artifact.factory.message.IMessage;
import com.sojoys.artifact.factory.session.ISession;
import com.sojoys.artifact.manager.SessionManager;

import akka.actor.ActorRef;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;

/**
 * Handler implementation for the echo server.
 */
@Sharable
public class NettyHandler extends ChannelInboundHandlerAdapter {
	static final Logger log = LoggerFactory.getLogger(NettyHandler.class);

//	private static final IMessage HEARTBEAT_SEQUENCE = MessageManager.newMesssage();

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Attribute<ISession> session = ctx.channel().attr(IChannelConstants.SESSION);
		boolean duplicate = session.compareAndSet(null, SessionManager.me().createSession(ctx.channel()));
		if (!duplicate) {
			ctx.channel().close();
			log.error("channelActive duplicate");
		}
	}
	
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		ISession session = ctx.channel().attr(IChannelConstants.SESSION).get();
		if (session == null) {
			log.error("Not Font Session");
			return;
		}
		if (IServer.SERVER_STATUS != ServerStatusEnum.RUNNING) {
			log.warn("Server Status -> {}", IServer.SERVER_STATUS);
		} else {
			if (msg instanceof IMessage) {
				ActorRef actorRef = session.getAttr(SessionConstent.ACTOR);
				if (actorRef != null) {
					actorRef.tell(new ClientMsg(session, (IMessage) msg), ActorRef.noSender());
				}else {
					Dispatcher.me().disp(session, (IMessage)msg);
				}
			}
		}
	}

	

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			String type = "";
			if (event.state() == IdleState.READER_IDLE) {
				type = "read idle";
			} else if (event.state() == IdleState.WRITER_IDLE) {
				type = "write idle";
			} else if (event.state() == IdleState.ALL_IDLE) {
				type = "all idle";
			}
			// ctx.writeAndFlush(HEARTBEAT_SEQUENCE).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
			ctx.channel().close();
			log.warn("{} 超时类型：{}", ctx.channel().remoteAddress(), type);
		} else {
			super.userEventTriggered(ctx, evt);
		}
	}

	@Override
	/**
	 * 异常中断
	 */
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		log.warn(cause.getMessage());
        ctx.channel().close();
	}

	@Override
	/**
	 * 正常中断
	 */
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Attribute<ISession> session = ctx.channel().attr(SessionConstent.STATE);
		ISession isession = session.getAndSet(null);
		if (isession != null) {
			isession.close();
		}
		super.channelInactive(ctx);
	}

}